package com.changan.service.impl;

import com.alibaba.fastjson.JSON;
import com.changan.entity.Menu;
import com.changan.mapper.MenuMapper;
import com.changan.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changan.utils.JsonUtils;
import com.changan.utils.MenuTreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author NieChangan
 * @since 2022-08-30
 */
@Service
public class MenuServiceImp extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 在这个方法中封装一个需要使用的菜单数json
     * @return
     */
    @Override
    public List<Menu> findMenuTree() {
//        List<Menu> menus = new ArrayList<>();
//        String key = "menuList";
//        //获取redis的操作对象
//        ValueOperations<String,Object> operations = redisTemplate.opsForValue();
//        //1.是否存在某个key
//        if(!redisTemplate.hasKey(key)){
//            //用来查询所有的菜单
//             menus = this.baseMapper.selectList(null);
//            String s = JsonUtils.objectToJson(menus);
//            //并且往redis中存一份
//            operations.set(key,s);
//        }else{
//            Object o = operations.get(key);
//             menus = JsonUtils.jsonToList(o.toString(), Menu.class);
////            System.out.println(menus);
//            //menus = JSON.parseObject(operations.get(key).toString(),ArrayList.class);
//        }

        List<Menu>menus = this.baseMapper.selectList(null);
        //用来构建菜单集合
        List<Menu> menuList = MenuTreeBuilder.build(menus);
        return menuList;
    }

    @Override
    public List<Long> findOpenIds() {
        List<Long> ids=new ArrayList<>();
        List<Menu> menus = this.baseMapper.selectList(null);
        if(!CollectionUtils.isEmpty(menus)){
            for (Menu menu : menus) {
                if(menu.getOpen()==1){
                    ids.add(menu.getId());
                }
            }
        }
        return ids;
    }
}
